package com.syh.jn.scm.domain.upstream.entity.sale;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.spring.SpringContextUtils;
import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.domain.AbstractSimpleAggregate;
import com.syh.jn.scm.domain.upstream.entity.logistics.UpLogisticsBill;
import com.syh.jn.scm.domain.upstream.repository.logistics.UpLogisticsBillReadRepository;
import com.syh.jn.scm.dto.support.FilesDto;
import com.syh.jn.scm.dto.upstream.sale.UpSaleReturnOrderSto;
import com.syh.jn.scm.exception.BusinessException;
import com.syh.jn.scm.service.api.supplier.logistics.enums.LogisticsBillEnums;
import com.syh.jn.scm.service.api.upstream.logistics.enums.UpLogisticsBillEnum;
import com.syh.jn.scm.service.api.upstream.sale.enums.UpSaleReturnOrderEnums;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.List;

/**
 * 销售退货单
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class UpSaleReturnOrder extends AbstractSimpleAggregate<Long> {
  public UpSaleReturnOrder(Long id) {
    this.id = id;
  }

  public UpSaleReturnOrder(UpSaleReturnOrderSto sto) {
    ExtAssert.notNull(sto, "对象为空");
    ExtBeanUtils.copyProperties(sto, this);
  }

  /**
   * 归属于那个服务商
   */
  private Long businessEntityId;
  /**
   * 采购退货订单编号
   */
  private String returnCode;
  /**
   * 对应采购订单id
   */
  private Long purchaseOrderId;
  /**
   * 上游供应商id
   */
  private Long upStreamCompanyId;
  /**
   * 采购退货订单状态(0：待确认 1：已确认 2：挂起 3:已生成对账单 -1：已取消)
   */
  private Short returnOrdState;
  /**
   * 字典id(退货原因)
   */
  private Long returnReasonId;
  /**
   * 收货人姓名
   */
  private String deliName;
  /**
   * 收货人联系电话
   */
  private String deliTel;
  /**
   * 运费金额
   */
  private BigDecimal totalFreight;
  /**
   * 收货地区编码
   */
  private String deliAreaCode;
  /**
   * 收货地址省 市 区
   */
  private String deliArea;
  /**
   * 收货人详细地址
   */
  private String deliAddress;
  /**
   * 发货地区编码
   */
  private String retDeliAreaCode;
  /**
   * 发货地址省 市 区
   */
  private String retDeliArea;
  /**
   * 发货人详细地址
   */
  private String retDeliAddress;
  /**
   * 备注
   */
  private String remark;
  /**
   * 录单人员id
   */
  private Long operatorId;
  /**
   * 物流生成状态(0：未生成物流单 1：部分生成物流单2：完成生成物流单)
   */
  private Short generatedState;
  /**
   * 发货状态(0：未发货 1：部分发货 2：完成发货)
   */
  private Short deliveryState;
  /**
   * 签收状态(0：未签收 1：部分签收 2：完成签收)
   */
  private Short collectState;
  /**
   * 退货订单总额
   */
  private BigDecimal returnTotalAmount;
  /**
   * 退货订单商品总额
   */
  private BigDecimal returnTotalGoodsAmount;
  /**
   * 退货出库总额
   */
  private BigDecimal returnTotalOutAmount;
  /**
   * 退货出库商品总额
   */
  private BigDecimal returnTotalOutGoodsAmount;
  /**
   * 退货签收总额
   */
  private BigDecimal returnTotalInAmount;
  /**
   * 退货签收商品总额
   */
  private BigDecimal returnTotalInGoodsAmount;
  /**
   * 优惠减免
   */
  private BigDecimal discount;
  /**
   * 对账单id
   */
  private Long statementId;
  /**
   * 录单日期
   */
  private Long inputDateTimestamp;
  /**
   * 发货时间(出库)
   */
  private Long deliveryTimestamp;
  /**
   * 收货时间
   */
  private Long receiptTimestamp;
  /**
   * 我方单据图片
   */
  private String mainSrcImages;
  /**
   * 对方单据图片
   */
  private String secondSrcImages;
  /**
   * 销售退货单明细
   */
  protected List<UpSaleReturnOrderItem> items;

  /**
   * 确认
   */
  public void confirm() {
    if (!this.returnOrdState.equals(UpSaleReturnOrderEnums.State.STAYCONFIRM.getStatus())) {
      throw new BusinessException("订单不是待确认状态,确认失败");
    }
    this.returnOrdState = UpSaleReturnOrderEnums.State.CONFIRM.getStatus();
  }

  /**
   * 取消确认
   */
  public void cancelConfirm() {
    if (!this.returnOrdState.equals(UpSaleReturnOrderEnums.State.CONFIRM.getStatus())) {
      throw new BusinessException("订单不是确认状态,取消确认失败");
    }
    if (!Short.valueOf("0").equals(this.generatedState)) {
      throw new BusinessException("订单已生成物流,取消确认失败");
    }
    this.returnOrdState = UpSaleReturnOrderEnums.State.STAYCONFIRM.getStatus();
  }

  /**
   * 挂起
   */
  public void handUp() {
    this.returnOrdState = UpSaleReturnOrderEnums.State.HANG.getStatus();
  }

  /**
   * 挂起订单还原待确认
   */
  public void reset() {
    this.returnOrdState = UpSaleReturnOrderEnums.State.STAYCONFIRM.getStatus();
  }

  /**
   * 取消
   */
  public void cancel() {
    if (!this.returnOrdState.equals(UpSaleReturnOrderEnums.State.STAYCONFIRM.getStatus())) {
      throw new BusinessException("订单不是待确认状态,不可以取消");
    }
    this.returnOrdState = UpSaleReturnOrderEnums.State.CANCEL.getStatus();
  }

  /**
   * 更新收货信息
   */
  public void collect(UpLogisticsBill bill) {
    if (this.collectState.equals(UpSaleReturnOrderEnums.CollectState.LOGISTICS_WHOLE_COLLECT.getStatus()))
      throw new BusinessException("签收失败，已全部签收！");
    //修改订单项发货数量
    bill.getItems().forEach(logisticsBillItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
          orderItem.setReturnInQuantity(orderItem.getReturnInQuantity() == null ? logisticsBillItem.getQuantity() :
                  orderItem.getReturnInQuantity().add(logisticsBillItem.getQuantity()));
        }
      });
    });
    this.receiptTimestamp = System.currentTimeMillis();
    this.calculateTotalReturnInAmount();
    this.calculateCollectStatus();
  }

  /**
   * 更新取消收货信息
   */
  public void cancelCollect(UpLogisticsBill bill) {
    UpLogisticsBillReadRepository logisticsBillReadRepository = (UpLogisticsBillReadRepository) SpringContextUtils.getBean(UpLogisticsBillReadRepository.class);
    bill = logisticsBillReadRepository.getById(bill.getId());
    //修改订单项发货数量
    bill.getItems().forEach(logisticsBillItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
          orderItem.setReturnInQuantity(orderItem.getReturnInQuantity() == null ? logisticsBillItem.getQuantity() :
                  orderItem.getReturnInQuantity().subtract(logisticsBillItem.getQuantity()));
        }
      });
    });
    this.receiptTimestamp = null;
    this.calculateTotalReturnInAmount();
    this.calculateCollectStatus();
  }

  //计算商品收货总额、订单收货总额
  private void calculateTotalReturnInAmount() {
    //计算销售退货订单入库商品总额
    BigDecimal totalAmount = BigDecimal.ZERO;
    for (UpSaleReturnOrderItem item : this.items) {
      totalAmount = totalAmount.add(item.calculateTotalInAmount());
    }
    this.returnTotalInGoodsAmount = totalAmount;

    //先计算出该订单下已发出、已签收状态的物流单据的物流费用
    UpLogisticsBillReadRepository logisticsBillReadRepository = (UpLogisticsBillReadRepository) SpringContextUtils.getBean(UpLogisticsBillReadRepository.class);
    Wrapper we = Wrapper.build();
    we.append(Restrictions.eq("orderId", this.id));
    we.append(Restrictions.eq("orderType", UpLogisticsBillEnum.ORDER_TYPE_SALE.getStatus()));
    we.append(Restrictions.eq("logisticsState", UpLogisticsBillEnum.DRIVER_SIGNIN.getStatus()));
    List<UpLogisticsBill> logisticsBills = logisticsBillReadRepository.getList(we);

    BigDecimal logisticsBillBeforeBuyFreight = BigDecimal.ZERO;//物流单据为预收买家的所有物流费用
    for (UpLogisticsBill logisticsBill : logisticsBills) {
      if (logisticsBill.getFreightTake() != null && logisticsBill.getFreightTake().equals(LogisticsBillEnums.FreightTake.BUY.getStatus())
              && logisticsBill.getFreightType().equals(LogisticsBillEnums.FreightType.BEFORE.getStatus()))
        logisticsBillBeforeBuyFreight = logisticsBillBeforeBuyFreight.add(logisticsBill.getTotalFreight());
    }

    //减去优惠金额
    if (this.discount != null) {
      totalAmount = totalAmount.subtract(this.discount);
    }
    //加上预收买家的运费金额
    totalAmount = totalAmount.add(logisticsBillBeforeBuyFreight);
    //计算销售退货订单入库总额
    this.returnTotalInAmount = totalAmount.compareTo(BigDecimal.ZERO) < 1 ? BigDecimal.ZERO : totalAmount;
    this.lastUpdateTimeStamp = System.currentTimeMillis();
  }

  //计算商品收货状态
  private void calculateCollectStatus() {
    //默认为已完全签收
    this.collectState = UpSaleReturnOrderEnums.CollectState.LOGISTICS_WHOLE_COLLECT.getStatus();
    //默认标记为未生成物流单
    boolean unCollected = true;

    for (UpSaleReturnOrderItem item : this.items) {
      //订单项已生成数量小于订单数量则为部分生成物流单
      if (this.collectState.equals(UpSaleReturnOrderEnums.CollectState.LOGISTICS_WHOLE_COLLECT.getStatus())
              && item.getReturnInQuantity().compareTo(item.getReturnQuantity()) < 0) {
        this.collectState = UpSaleReturnOrderEnums.CollectState.LOGISTICS_PART_COLLECT.getStatus();
      }

      //订单项已发货数量大于0 则不是未发货
      if (unCollected && item.getReturnInQuantity().compareTo(BigDecimal.ZERO) > 0) {
        unCollected = false;
      }
    }
    if (unCollected) {
      this.collectState = UpSaleReturnOrderEnums.CollectState.LOGISTICS_UN_COLLECT.getStatus();
      this.receiptTimestamp = null;
    }
  }

  /**
   * 生成对账单
   */
  public void generating(Long statementOfAccountId) {
    if (this.collectState.equals(UpSaleReturnOrderEnums.CollectState.LOGISTICS_UN_COLLECT.getStatus())) {
      throw new BusinessException("销售退货单" + this.returnCode + "未签收，无法生成对账单");
    }
    if (this.returnOrdState.equals(UpSaleReturnOrderEnums.State.STATEMENT.getStatus())) {
      throw new BusinessException("销售退货单已生成对账单!");
    }
    this.statementId = statementOfAccountId;
    this.returnOrdState = UpSaleReturnOrderEnums.State.STATEMENT.getStatus();
  }

  /**
   * 取消对账单
   */
  public void cancelGenerating() {
    if (!this.returnOrdState.equals(UpSaleReturnOrderEnums.State.STATEMENT.getStatus())) {
      throw new BusinessException("销售单已取消对账单!");
    }
    this.statementId = null;
    this.returnOrdState = UpSaleReturnOrderEnums.State.CONFIRM.getStatus();
  }

  /**
   * 下游采购订单上传图片
   *
   * @param dto
   */
  public void upload(FilesDto dto) {
    this.secondSrcImages = dto.getFiles();
  }
}
